<template>
  <div v-bkloading="{ isLoading }">
    <bk-select ref="select" v-bind="$attrs" :clearable="true" ext-popover-cls="account-select-menu-list" searchable
      :value="value" @change="handleChange" @toggle="handleClick">
      <auth-option v-for="option in wholeList" :id="option.id" :key="option.id" auth="account/use" :name="option.alias"
        :permission="option.canUse" :resource-id="option.id">
        <div>{{ option.alias }}</div>
      </auth-option>
    </bk-select>
  </div>
</template>
<script>
import SlurmJobService from '@service/slurm';

export default {
  props: {
    value: {
      type: [
        Number, String,
      ],
    },
  },
  data() {
    return {
      isLoading: false,
      wholeList: []
    };
  },
  computed: {},
  watch: {},
  created() {
    this.fetchAppAccount();
  },
  methods: {
    /**
     * @desc 获取完整的账号列表
     */
    fetchAppAccount() {
      this.isLoading = true;
      SlurmJobService.getGpuTypes().then(({ data }) => {
        this.wholeList = Object.freeze(data.map(item => {
          return {
            ...item,
            id: item.name,
            alias: item.name,
            canUse: true
          }
        }));
      }).finally(() => {
        this.isLoading = false;
      });
    },
    /**
     * @desc select 的下面板展开时重新获取最新账号数据
     * @param {Boolean} toogle 下拉面板的展开收起状态
     */
    handleClick(toggle) {
      if (toggle) {
        this.fetchAppAccount();
      }
    },
    /**
     * @desc 用户选中账号
     * @param {Number} 选中的账号ID
     */
    handleChange(value) {
      if (value === this.value) {
        return;
      }
      this.$emit('input', value);
      this.$emit('change', value);
    },
  },
};
</script>
